import { getTableData, getTable, deleteTable } from "@/api";
import { TableObject } from "@/type/global";
import { Button, Card, Drawer, Modal } from "antd";
import React, { useEffect, useState } from "react";
import TableCard from "../TableCard";
import { Input } from "antd";
const { Search } = Input;
const TableDrawer: React.FC<{ onImport: (data: TableObject) => void }> = (props) => {

    const [visible, setVisible] = useState(false);

    const [tableList, setTableList] = useState<TableObject[]>();

    useEffect(() => {
        if (visible) {
            init()
        }
    }, [visible]);

    function init() {
        getTableData().then(res => {
            setTableList(res);
        })
    }

    function handleImport(data: TableObject) {
        props.onImport(data);
        setVisible(false)
    }

    function handleSearch(value: string) {
        getTable(value).then(res => {
            setTableList(res);
        })
    }

    function handleDelete(id: string | number) {
        Modal.confirm({
            title: '提示',
            content: '是否删除该表?',
            onOk: () => {
                deleteTable(id).then(res => {
                    init();
                })
            }
        })
    }

    return <div style={{ marginTop: '8px' }}>
        <Button onClick={() => setVisible(true)} block>导入表</Button>

        <Drawer width={600} onClose={() => setVisible(false)} title="选择表" open={visible}>
            <Card title="表信息">
                <Search placeholder="请输入表描述" onSearch={handleSearch} style={{ width: '300px', marginBottom: '24px' }}></Search>
                {
                    tableList?.map((item, index) => <TableCard onDelete={handleDelete} onImport={handleImport} key={index} data={item}></TableCard>)
                }
            </Card>
        </Drawer>
    </div>
}

export default TableDrawer;